package com.lmk.mkcc.mq.consumer;

import com.alibaba.fastjson.JSON;
import com.lmk.mkcc.domain.PayOrder;
import com.lmk.mkcc.dto.PayDto;
import com.lmk.mkcc.enums.GlobalErrorCode;
import com.lmk.mkcc.service.IPayOrderService;
import com.lmk.mkcc.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
@Slf4j
@RocketMQMessageListener(
        consumerGroup = "corse-order-sw-consumer-group",
        topic = "corse-order-sw-topic",
        selectorExpression = "corse-order-sw-tag"
)
public class CourseOrderPayConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        // 1.获取消息体
        byte[] body = messageExt.getBody();
        // 2.将数组转化为string类型
        String s = new String(body, StandardCharsets.UTF_8);
        // 3.将字符串转化为对象
        PayDto payDto = JSON.parseObject(s, PayDto.class);
        AssertUtil.isNotNull(payDto, GlobalErrorCode.NO_PAYDTO_ERROR);

        // 4.根据订单编号查询在支付单中是否有该订单
        String orderNo = payDto.getOrderNo();
        PayOrder payOrder = payOrderService.getByOrderNo(orderNo);
        // 如果在支付单中有订单，说明重复提交，直接return
        if (payOrder!=null){
            return;
        }
        // 保存到支付单中
        PayOrder payOrder1 = new PayOrder();
        payOrder1.setCreateTime(new Date());
        payOrder1.setAmount(payDto.getTotalAmount());
        payOrder1.setExtParams(payDto.getExtParams());
        payOrder1.setOrderNo(orderNo);
        payOrder1.setPayType(payDto.getPayType());
        payOrder1.setPayStatus(PayOrder.WAIT_PAY);
        payOrder1.setUserId(payDto.getUserId());
        payOrder1.setSubject(payDto.getTitle());
        payOrderService.insert(payOrder1);
    }
}
